package blog.spring.web.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import blog.core.exception.FormParamErrorException;
import blog.spring.db.entity.User;
import blog.spring.db.service.IUserService;

public class CookieUtils {

	public enum LoginType {
		LOGIN, LOGOUT
	}

	/**
	 * 根据cookie判断是否登陆
	 *
	 * @param req
	 *            HttpServletRequest对象
	 * @param userService
	 * @return 登陆返回当前用户，未登录返回null
	 */
	public static User isLogin(HttpServletRequest req, IUserService userService) {

		Cookie userCookie = null;
		User user = null;
		for (Cookie cookie : req.getCookies() == null ? new Cookie[] {} : req
				.getCookies()) {
			if ("user".equals(cookie.getName()))
				userCookie = cookie;
		}
		if (userCookie != null && userCookie.getValue() != null) {
			String username = userCookie.getValue().split(":")[0];
			String password = userCookie.getValue().split(":")[1];
			try {
				return userService.login(username, password);
			} catch (FormParamErrorException e) {
				System.err.println("cookie失效.");
				return null;
			}
		}
		return user;
	}

	/**
	 * 设置登陆Cookie
	 *
	 * @param req
	 *            HttpServletRequest对象
	 * @param resp
	 *            HttpServletResponse对象
	 * @param user
	 *            当前登陆成功的user对象
	 */
	public static void setLoginCookie(HttpServletRequest req,
			HttpServletResponse resp, User user, LoginType type) {
		Cookie userCookie = null;
		if (user == null)
			userCookie = new Cookie("user", null);
		else
			userCookie = new Cookie("user", user.getUserName() + ":"
					+ user.getPassWord());
		userCookie.setPath("/");
		switch (type) {
		case LOGIN:
			userCookie.setMaxAge(1000 * 60 * 24 * 30);
			break;
		case LOGOUT:
			userCookie.setMaxAge(0);
			break;
		}
		resp.addCookie(userCookie);
	}
}